<template>
  <div class="app-container">
    <el-row gutter="20">
      <el-col :span="4" :xs="24">
        <!--厂家数据-->
          <div class="head-container">
            <el-input
              v-model="supplierName"
              placeholder="请输入供货商名进行搜索"
              clearable
              size="small"
              prefix-icon="el-icon-search"
              style="margin-bottom: 20px"
            />
          </div>
          <div class="head-container">
            <el-tree
              :data="supplierOptions"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              default-expand-all
              @node-click="handleNodeClick"
            />
          </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="销售日期" prop="saleDate">
            <el-date-picker clearable
                            v-model="queryParams.saleDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择销售记录日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="发票状态" prop="invoice">
            <el-select v-model="queryParams.invoice" placeholder="请选择发票状态">
              <el-option
                v-for="dict in dict.type.bk_invoice_status"
                :key="dict.value"
                :label="dict.label"
                clearable
                @keyup.enter.native="handleQuery"
                :value="dict.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品名" prop="productName">
            <el-select v-model="queryParams.productId" filterable placeholder="请选择采购商品名" @change="getProductModelList(queryParams.productId)">
              <el-option
                v-for="item in itemNames"
                :key="item.productName"
                :label="item.productName"
                clearable
                @keyup.enter.native="handleQuery"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品型号" title="请选择采购商品型号名" prop="productModel">
            <el-select v-model="queryParams.productModel" filterable placeholder="请选择采购商品名">
              <el-option
                v-for="item in itemModels"
                :key="item.id"
                :label="item.productModel"
                clearable
                :value="item.productModel">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="销售人" prop="seller">
            <el-input
              v-model="queryParams.seller"
              placeholder="请输入销售人"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="商品状态" prop="productEnable">
            <el-select v-model="queryParams.productEnable" placeholder="请选择商品状态">
              <el-option
                v-for="dict in dict.type.bk_product_enable"
                :key="dict.value"
                :label="dict.label"
                clearable
                @keyup.enter.native="handleQuery"
                :value="dict.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="付款客户" prop="customerId">
            <el-select v-model="queryParams.customerId" filterable placeholder="请选择商品状态">
              <el-option
                v-for="customer in customers"
                :key="customer.id"
                :label="customer.customerName"
                clearable
                @keyup.enter.native="handleQuery"
                :value="customer.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:sale:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['system:sale:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:sale:remove']"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['system:sale:export']"
            >导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="saleList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="销售记录id" align="center" prop="id" />
          <el-table-column label="销售记录日期" align="center" prop="saleDate" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.saleDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="已付货款" align="center" prop="paymentPaid" />
          <el-table-column label="未付货款" align="center" prop="paymentUnpaid" />
          <el-table-column label="发票状态" align="center" prop="invoice">
            <template v-slot="scope">
              <dict-tag :options="dict.type.bk_invoice_status" :value="scope.row.invoice"/>
            </template>
          </el-table-column>
          <el-table-column label="销售人" align="center" prop="seller" />
          <el-table-column label="销售商品名" align="center" prop="productName"/>
          <el-table-column label="销售商品型号" align="center" prop="productModel"/>
          <el-table-column label="销售数量" align="center" prop="saleQuantity" />
          <el-table-column label="销售价格" align="center" prop="salePrice" />
          <el-table-column label="商品状态" align="center" prop="productEnable">
            <template v-slot="scope">
              <dict-tag :options="dict.type.bk_product_enable" :value="scope.row.productEnable"/>
            </template>
          </el-table-column>
          <el-table-column label="付款客户" align="center" prop="customerName"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:sale:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:sale:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改销售记录对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="销售日期" prop="saleDate">
              <el-date-picker clearable
                              v-model="form.saleDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择销售记录日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="已付货款" prop="paymentPaid">
              <el-input v-model="form.paymentPaid" placeholder="请输入销售记录已付货款" />
            </el-form-item>
            <el-form-item label="未付货款" prop="paymentUnpaid">
              <el-input v-model="form.paymentUnpaid" placeholder="请输入销售记录未付货款" />
            </el-form-item>
            <el-form-item label="发票状态" prop="invoice">
              <el-select v-model="form.invoice" placeholder="请选择发票状态">
                <el-option
                  v-for="dict in dict.type.bk_invoice_status"
                  :key="dict.value"
                  :label="dict.label"
                  clearable
                  @keyup.enter.native="handleQuery"
                  :value="dict.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="销售人" prop="seller">
              <el-input v-model="form.seller" placeholder="请输入销售人" />
            </el-form-item>
            <el-form-item label="商品名" prop="productName">
              <el-select v-model="form.productName" filterable placeholder="请选择采购商品名" @change="getProductModelList(form.productName)">
                <el-option
                  v-for="item in itemNames"
                  :key="item.productName"
                  :label="item.productName"
                  clearable
                  @keyup.enter.native="handleQuery"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品型号" title="请选择采购商品型号名" prop="productId">
              <el-select v-model="form.productId" filterable placeholder="请选择商品商品名">
                <el-option
                  v-for="item in itemModels"
                  :key="item.id"
                  :label="item.productModel"
                  clearable
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="销售数量" prop="saleQuantity">
              <el-input v-model="form.saleQuantity" placeholder="请输入本次销售数量" />
            </el-form-item>
            <el-form-item label="销售价格" prop="salePrice">
              <el-input v-model="form.salePrice" placeholder="请输入本次销售价格" />
            </el-form-item>
            <el-form-item label="付款客户" prop="customerId">
              <el-select v-model="form.customerId" filterable placeholder="请选择商品状态">
                <el-option
                  v-for="customer in customers"
                  :key="customer.id"
                  :label="customer.customerName"
                  clearable
                  @keyup.enter.native="handleQuery"
                  :value="customer.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { listSale, getSale, delSale, addSale, updateSale } from "@/api/bookkeeping/sale";
import {treeselect} from "@/api/transaction/supplier";
import {listProductModel, listProductName} from "@/api/inventory/product";
import {listCustomer} from "@/api/transaction/customer";

export default {
  name: "Sale",
  dicts: ['bk_invoice_status','bk_product_enable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 销售记录表格数据
      saleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 供货商名
      supplierName: undefined,
      // 供货商选项
      supplierOptions: undefined,
      // 商品名数据
      itemNames: undefined,
      // 商品型号数据
      itemModels: undefined,
      // 客户数据
      customers: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        saleDate: null,
        paymentPaid: null,
        paymentUnpaid: null,
        invoice: null,
        seller: null,
        saleQuantity: null,
        salePrice: null,
        productId: null,
        productName: null,
        productModel: null,
        customerId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        saleDate: [
          { required: true, message: "销售记录日期不能为空", trigger: "blur" }
        ],
        paymentPaid: [
          { required: true, message: "销售记录已付货款不能为空", trigger: "blur" }
        ],
        paymentUnpaid: [
          { required: true, message: "销售记录未付货款不能为空", trigger: "blur" }
        ],
        invoice: [
          { required: true, message: "销售记录是否开具发票，默认未开具，未开具0，增值税1，普通票2不能为空", trigger: "blur" }
        ],
        saleQuantity: [
          { required: true, message: "本次销售数量不能为空", trigger: "blur" }
        ],
        salePrice: [
          { required: true, message: "本次销售价格不能为空", trigger: "blur" }
        ],
        productName: [
          { required: true, message: "商品名不能为空", trigger: "blur" }
        ],
        productId: [
          { required: true, message: "商品型号不能为空", trigger: "blur" }
        ],
        customerId: [
          { required: true, message: "客户不能为空", trigger: "blur" }
        ]
      }
    };
  },
  watch: {
    // 根据名称筛选供货商树
    supplierName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询销售记录列表 */
    getList() {
      this.loading = true;
      listSale(this.queryParams).then(response => {
        this.saleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      this.getTreeSelect();
      this.getProductNameList();
      this.getCustomerList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        saleDate: null,
        paymentPaid: null,
        paymentUnpaid: 0,
        invoice: null,
        seller: '李合群',
        saleQuantity: null,
        salePrice: null,
        productId: null,
        productName: null,
        customerId: null
      };
      this.resetForm("form");
    },
    /** 查询产品名 **/
    getProductNameList(){
      listProductName().then(response => {
        this.itemNames = response.rows;
      })
    },
    /** 查询选中产品型号 **/
    getProductModelList(id){
      this.queryParams.productModel = null;
      this.form.productId = null;
      listProductModel(id).then(response => {
        this.itemModels = response;
      })
    },
    /**
     * 查询客户列表
     */
    getCustomerList(){
      listCustomer().then(response => {
        this.customers = response.rows;
      });
    },
    /** 查询部门下拉树结构 */
    getTreeSelect() {
      treeselect().then(response => {
        this.supplierOptions = response.data;
      });
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.supplierId = data.id;
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.productId = null;
      this.itemModels = null;
      this.queryParams.supplierId = null;
      this.queryParams.customerId = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加销售记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSale(id).then(response => {
        this.itemModels = [{
          id: parseInt(response.data.productId),
          productModel: String(response.data.productModel)
        }];
        this.form = response.data;
        this.form.invoice = String(response.data.invoice);
        this.form.productId = parseInt(response.data.productId)
        this.open = true;
        this.title = "修改销售记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSale(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSale(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除销售记录编号为"' + ids + '"的数据项？').then(function() {
        return delSale(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/sale/export', {
        ...this.queryParams
      }, `sale_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
